import os
import logging
import importlib
from .dalchemy_parser import DalchemyParser
from .json_parsers import *
from .line_parsers import *
from typing import Dict

PARSER_REGISTRY: Dict[str, DalchemyParser] = {}


# 注册函数
def register_parser(name):
    def register_parser_fn(cls):
        assert issubclass(cls, DalchemyParser)
        if cls in PARSER_REGISTRY.values():
            raise ValueError("Cannot register duplicate parser ({})".format(name))
        PARSER_REGISTRY[name] = cls
        return cls

    return register_parser_fn


def import_models(import_dir, namespace):
    for file in os.listdir(import_dir):
        path = os.path.join(import_dir, file)
        if (
                not file.startswith("_")
                and not file.startswith(".")
                and (file.endswith(".py") or os.path.isdir(path))
        ):
            import_name = file[: file.find(".py")] if file.endswith(".py") else file
            importlib.import_module(namespace + "." + import_name)


# automatically import any Python files in the infer/ directory
import_dir = os.path.dirname(__file__)
import_models(import_dir, "dalchemy.parsers")


def build_parser(name):
    return PARSER_REGISTRY.get(name, DalchemyParser)()
